// API 基础URL
const API_URL = 'http://localhost:3000/api';

// DOM元素
const postsContainer = document.getElementById('postsContainer');
const postFormContainer = document.getElementById('postFormContainer');
const postForm = document.getElementById('postForm');
const showPostFormBtn = document.getElementById('showPostForm');
const cancelPostBtn = document.getElementById('cancelPost');
const postTemplate = document.getElementById('postTemplate');

// 事件监听器
document.addEventListener('DOMContentLoaded', loadPosts);
showPostFormBtn.addEventListener('click', togglePostForm);
cancelPostBtn.addEventListener('click', togglePostForm);
postForm.addEventListener('submit', handlePostSubmit);

// 加载所有文章
async function loadPosts() {
    try {
        const response = await fetch(`${API_URL}/posts`);
        if (!response.ok) throw new Error('加载失败');
        
        const posts = await response.json();
        displayPosts(posts);
    } catch (error) {
        console.error('加载文章失败:', error);
        postsContainer.innerHTML = '<div class="text-center text-red-500">加载失败，请刷新重试</div>';
    }
}

// 显示文章列表
function displayPosts(posts) {
    if (posts.length === 0) {
        postsContainer.innerHTML = '<div class="text-center text-gray-500 py-8">暂无信息，快来发布第一条吧！</div>';
        return;
    }

    postsContainer.innerHTML = '';
    posts.forEach(post => {
        const postElement = createPostElement(post);
        postsContainer.appendChild(postElement);
    });
}

// 创建文章元素
function createPostElement(post) {
    const template = postTemplate.content.cloneNode(true);
    
    // 填充文章数据
    template.querySelector('.post-title').textContent = post.title;
    template.querySelector('.post-content').textContent = post.content;
    template.querySelector('.post-author').textContent = post.author;
    template.querySelector('.post-date').textContent = formatDate(post.created_at);
    template.querySelector('.comment-count').textContent = '0';
    
    // 添加事件监听器
    const toggleBtn = template.querySelector('.toggle-comments');
    const commentsSection = template.querySelector('.comments-section');
    const commentForm = template.querySelector('.comment-form');
    
    toggleBtn.addEventListener('click', () => toggleComments(post.id, commentsSection, toggleBtn));
    commentForm.addEventListener('submit', (e) => handleCommentSubmit(e, post.id, commentsSection));
    
    // 设置文章ID
    template.querySelector('.comments-section').dataset.postId = post.id;
    
    return template;
}

// 切换评论区显示
async function toggleComments(postId, commentsSection, toggleBtn) {
    const isHidden = commentsSection.classList.contains('hidden');
    
    if (isHidden) {
        // 加载评论
        try {
            const response = await fetch(`${API_URL}/posts/${postId}`);
            if (!response.ok) throw new Error('加载评论失败');
            
            const post = await response.json();
            displayComments(post.comments, commentsSection);
            commentsSection.classList.remove('hidden');
            toggleBtn.innerHTML = `<i class="fas fa-comments mr-1"></i>隐藏评论`;
        } catch (error) {
            console.error('加载评论失败:', error);
        }
    } else {
        commentsSection.classList.add('hidden');
        toggleBtn.innerHTML = `<i class="fas fa-comments mr-1"></i><span class="comment-count">0</span> 评论`;
    }
}

// 显示评论
function displayComments(comments, commentsSection) {
    const commentsList = commentsSection.querySelector('.comments-list');
    const commentCount = commentsSection.querySelector('.comment-count');
    
    if (comments.length === 0) {
        commentsList.innerHTML = '<p class="text-gray-500">暂无评论</p>';
    } else {
        commentsList.innerHTML = '';
        comments.forEach(comment => {
            const commentElement = createCommentElement(comment);
            commentsList.appendChild(commentElement);
        });
    }
    
    if (commentCount) {
        commentCount.textContent = comments.length;
    }
}

// 创建评论元素
function createCommentElement(comment) {
    const div = document.createElement('div');
    div.className = 'comment-item fade-in';
    div.innerHTML = `
        <div class="flex justify-between items-start mb-2">
            <span class="comment-author">${comment.author}</span>
            <span class="comment-date">${formatDate(comment.created_at)}</span>
        </div>
        <p class="comment-content">${comment.content}</p>
    `;
    return div;
}

// 处理发布文章
async function handlePostSubmit(e) {
    e.preventDefault();
    
    const title = document.getElementById('postTitle').value.trim();
    const content = document.getElementById('postContent').value.trim();
    const author = document.getElementById('postAuthor').value.trim();
    
    if (!title || !content || !author) {
        alert('请填写所有必填项');
        return;
    }
    
    try {
        const response = await fetch(`${API_URL}/posts`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ title, content, author })
        });
        
        if (!response.ok) throw new Error('发布失败');
        
        const newPost = await response.json();
        
        // 清空表单
        postForm.reset();
        togglePostForm();
        
        // 重新加载文章列表
        await loadPosts();
        
        // 显示成功消息
        showMessage('发布成功！', 'success');
    } catch (error) {
        console.error('发布文章失败:', error);
        showMessage('发布失败，请重试', 'error');
    }
}

// 处理添加评论
async function handleCommentSubmit(e, postId, commentsSection) {
    e.preventDefault();
    
    const authorInput = commentsSection.querySelector('.comment-author');
    const contentInput = commentsSection.querySelector('.comment-content');
    
    const author = authorInput.value.trim();
    const content = contentInput.value.trim();
    
    if (!author || !content) {
        alert('请填写昵称和评论内容');
        return;
    }
    
    try {
        const response = await fetch(`${API_URL}/posts/${postId}/comments`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ content, author })
        });
        
        if (!response.ok) throw new Error('评论失败');
        
        const newComment = await response.json();
        
        // 清空表单
        authorInput.value = '';
        contentInput.value = '';
        
        // 重新加载评论
        const postResponse = await fetch(`${API_URL}/posts/${postId}`);
        const post = await postResponse.json();
        displayComments(post.comments, commentsSection);
        
        showMessage('评论成功！', 'success');
    } catch (error) {
        console.error('添加评论失败:', error);
        showMessage('评论失败，请重试', 'error');
    }
}

// 切换发布表单显示
function togglePostForm() {
    postFormContainer.classList.toggle('hidden');
    if (!postFormContainer.classList.contains('hidden')) {
        document.getElementById('postTitle').focus();
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);
    
    if (diffMins < 1) return '刚刚';
    if (diffMins < 60) return `${diffMins}分钟前`;
    if (diffHours < 24) return `${diffHours}小时前`;
    if (diffDays < 7) return `${diffDays}天前`;
    
    return date.toLocaleDateString('zh-CN');
}

// 显示消息
function showMessage(text, type = 'info') {
    const messageDiv = document.createElement('div');
    messageDiv.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
        type === 'success' ? 'bg-green-500 text-white' : 
        type === 'error' ? 'bg-red-500 text-white' : 
        'bg-blue-500 text-white'
    }`;
    messageDiv.textContent = text;
    
    document.body.appendChild(messageDiv);
    
    setTimeout(() => {
        messageDiv.remove();
    }, 3000);
}

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    if (e.ctrlKey && e.key === 'n') {
        e.preventDefault();
        togglePostForm();
    }
});
